// pages/my/cash/affirmRecharge.js
const App = getApp();
const util = require('../../../utils/util.js');
const api = require('../../../utils/api.js');


//支付方式
var payType = ''

Page({
  data: {   
    items: [
      {
        name: 'wxpay', value: '微信支付',
        memo: '推荐安装微信5.0及以上版本的用户使用',
        img: '../../../image/my/u2174.png',
        isSelect: true,//   暂时只有微信支付，默认选中
      }
    ],
    form: {
      name: '',
      is_def: 0,
    },
    //页面数据
    stores_id: '',
    goods_id: '',
    goods_data: '',
    buyerMsg: '',
    deliveryMsg: '',
    wetPayData: '',
    //OpenIdData: '',
    rps_order: '',
    //页面跳转
    tapType_set: '',
    secondIndex: 0,
    server_val:'',
    num:"",
    //禁止按钮
    disabled:false,
  },
  //初始化数据加载
  onLoad: function (option) {
    this.setData({
      goods_id: option.goods_id,
      stores_id: option.stores_id,
      num: App.globalData.num
    })

    this.getGoodsMsg(),
      this.getDeliveryMsg()
  },

  /**
   * 生命周期函数--监听页面显示--回退部分刷新
   */
  onShow: function () {
    this.getDeliveryMsg();
    //重新启动按钮点击
    this.setData({
      disabled: false
    })
  },

  getGoodsMsg() {
    const self = this;

    let data = {
      service: 'goods.psGoodsDetailFind',
      params: '{"goods_id":""}',

      url_type: 'goods',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var jsons = JSON.parse(data.params);
    jsons["goods_id"] = self.data.goods_id;
    data.params = JSON.stringify(jsons);

    //标签状态切换查询
    //let sign = util.getSign(data);
    //data.sign = sign;

    api.reqData({
      data,
      success: (res) => {
        //根据pic_info获得头像突破
        let list_new = util.mergePicMsg(res.data.data.doc_url, res.data.data.list);
        

        res.data.data.list = list_new;
        console.log(res.data);
        console.log(res.data);
        res.data.data.list[0].delivery = (res.data.data.list[0].ts_price * self.data.num).toFixed(2);
        res.data.data.list[0].goods_unit = (res.data.data.list[0].market_price * self.data.num).toFixed(2);

        self.setData({   
          goods_data: res.data.data,
        })
      },
    })
  },

  //跳转修改地址信息
  toDeliveryMsg(e) {
    wx.navigateTo({
      url: '/pages/my/address/list/list'
    })
  },

  //加载收获地址信息
  getDeliveryMsg() {
    const self = this;
    let data = {
      service: 'member.consumerAddressFind',
      params: '{"is_major_addr":"Y","consumer_id":"1111"}',
      url_type: 'member',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var jsons = JSON.parse(data.params);
    jsons["consumer_id"] = App.globalData.memberInfo.member_id;
    data.params = JSON.stringify(jsons);


    api.reqData({
      data,
      success: (res) => {
        //这个得写法和格式 setData({........})
        console.log("收获地址=======" + res.data);
        self.setData({
          deliveryMsg: res.data.data[0],
        })
      },
    })
  },

  //获取js_code
  getJscode() {
    const self = this;
    //let appid = App.globalData.appid;
    //let secret = App.globalData.appkey;
    //发起网络请求
    wx.login({
      success: function (res) {
        if (res.code) {

              //创建精品自营订单

              self.setData({
                js_code: res.code
              })

              self.createOrder();

        }
      }
    })
  },

  /** 创建会过自营订单 */
  createOrder() {
    const self = this;
    console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    console.log(self.data.goods_data.list[0])
    console.log(self.data.goods_data.list[0].data_source)
    if (self.data.goods_data.list[0].data_source == "huiguo") {
      self.setData({
        server_val: 'order.consumer.huiguoOrderCreate'
      })
    } else if (self.data.goods_data.list[0].data_source == "meitianhui"){
      self.setData({
        server_val: 'order.consumer.OwnOrderCreate'
      })
    }
    console.log("#$%^&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
    console.log(self.data.num)
    let data = {
      service: self.data.server_val,
      //goods_code 从哪里来
      params: '{"consumer_id":"","stores_name":"","version_number":"","goods_url":"","recommend_stores_id":"","goods_code":"","mobile":"","member_id":"","nick_name":"","order_type":"","data_source":"SJLY_17","payment_way_key":"ZFFS_02","delivery_address":"","remark":"买家没有留言哟","contact_person":"","contact_tel":"","qty":"' + self.data.num +'"}',
      url_type: 'opsorder',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    //组装动态数据
    var json = JSON.parse(data.params);
    console.log("#$%^&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
    console.log(json)
    //组装第一层数据
    json.goods_code = self.data.goods_data.list[0].goods_code;
    json.recommend_stores_id = self.data.stores_id;
    json.mobile = App.globalData.memberInfo.mobile;
    json.member_id = App.globalData.memberInfo.member_id;
    json.consumer_id = App.globalData.memberInfo.member_id;
    json.nick_name = App.globalData.memberInfo.nick_name;
    json.version_number = App.globalData.version;       //创建会过自营时传版本号
    //新加会过商品，下单需要区分出订单类型
    json.order_type = self.data.goods_data.list[0].data_source;
    
    //为配合运营后台，添加字段
    let deliveryMsg = self.data.deliveryMsg;
    json.delivery_address = deliveryMsg.area_desc + "" + deliveryMsg.address;
    json.remark = self.data.buyerMsg;
    json.contact_person = deliveryMsg.consignee;
    json.contact_tel = deliveryMsg.mobile;

    data.params = JSON.stringify(json);
    //let sign = util.getSign(data);
    //data.sign = sign;
    api.reqData({
      data,
      success: (res) => {
        console.log(res.data);
        if (res.data.rsp_code === "succ") {
          console.log(JSON.stringify(res.data));
          self.setData({
            rps_order: res.data
          })
          this.wetPayPre();
        } else {
          wx.showToast({
            title: '此商品已领取过',
            icon: 'fail',
            duration: 3000
          });
        }
      },
    })
  },

  submitForm(e) {
    //判断收获地址为空的情况
    if (this.data.deliveryMsg == undefined) {
      wx.showToast({
        title: '收获信息不能为空',
        icon: 'fail',
        duration: 2000
      })
      return
    }
    this.getJscode();
    //禁止重复点击按钮
    this.setData({
      disabled: true
    })
  },

  /* 获取prePayId */
  wetPayPre() {
    const self = this;
    console.log("payTpe>>>>>>>>" + payType)
    console.log(self.data.goods_data.list[0])
    console.log(self.data.goods_data.list[0].data_source)


    //精品自营商品支付(带存存储客户留言)
    let data = {

      service: 'finance.miniAppWechatPay',
      params: '{"data_source":"SJLY_17","payment_way_key":"ZFFS_02","detail":"", "amount":"", "seller_id":"10000001","buyer_id":"","js_code":"oA9D20EZogOYpVNKYEjfAVUWfGaQ","order_type_key":"","out_trade_body":"","order_type":"meitianhui"}',

      url_type: 'finance',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }
    console.log(data.params)
    var json = JSON.parse(data.params);
    //组装第一层数据

    if (self.data.goods_data.list[0].data_source=='huiguo'){
        json.detail = '会过';
        json.order_type_key = 'DDLX_07'         //  3月13号修改
    }else{
        json.detail = '自营';
        json.order_type_key = 'DDLX_07'
    }
    console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
    console.log(json)
    //json.amount = self.data.goods_data.list[0].market_price;
    json.amount = (self.data.goods_data.list[0].market_price * self.data.num).toFixed(2);   
    json.buyer_id = App.globalData.memberInfo.member_id;
    //json.openid = App.globalData.openid;
    json.js_code = self.data.js_code;
    json.order_type = self.data.goods_data.list[0].data_source;
    //json.order_id = self.data.rps_order.data.order_id;

    //组装第二层数据
    let out_trade_body = {};
    let deliveryMsg = self.data.deliveryMsg;
    out_trade_body["data_source"] = 'SJLY_17';  
    out_trade_body["payment_way_key"] = 'ZFFS_02'; // 微信小程序 支付方式 ZFFS_26  
    out_trade_body["delivery_address"] = deliveryMsg.area_desc + "" + deliveryMsg.address;
    out_trade_body["contact_person"] = deliveryMsg.consignee;
    out_trade_body["contact_tel"] = deliveryMsg.mobile;
    out_trade_body["remark"] = self.data.buyerMsg;
    out_trade_body["order_id"] = self.data.rps_order.data.order_id;

    json.out_trade_body = out_trade_body;
    data.params = JSON.stringify(json);

    //let sign = util.getSign(data);
    //data.sign = sign;
    api.reqData({
      data,
      success: (res) => {
        //这个得写法和格式 setData({........})
        console.log(res.data + "---------------------------");
        console.log(JSON.stringify(res.data) + "---------------------------");
        if (res.data.rsp_code === 'succ') {
          self.setData({
            wetPayData: res.data.data
          })
          //微信支付
          self.pay()
        } else {
          wx.showToast({
            title: res.data.error_msg,
            icon: 'fail',
            duration: 3000
          })
        }
      },
    })
  },


  /* 微信支付 */
  pay: function () {
    const self = this;
    wx.requestPayment({
      timeStamp: self.data.wetPayData.timeStamp,
      nonceStr: self.data.wetPayData.nonceStr,
      package: self.data.wetPayData.package,
      signType: 'MD5',
      paySign: self.data.wetPayData.paySign,
      success: function (res) {
        // success  
        console.log(res)
        App.globalData.secondIndex = 2,
          App.globalData.status = 'confirmed',
          wx.switchTab({
           url: '/pages/buy/orderlist/orderlist',
            success: function (e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
               page.initData();
               page.onLoad();
            } 
          }) 
      },
       fail: function (res) {
        // fail  
        //跳转到订单待付款页面
        App.globalData.secondIndex = 1,
        App.globalData.status = 'processing',
        wx.switchTab({
          url: '/pages/buy/orderlist/orderlist',
/*             success: function (e) {
              var page = getCurrentPages().pop();

              console.log(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<")
              console.log(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<")
              console.log("getCurrentpges>>>>>>>>")
              console.log(getCurrentPages())
              console.log("getCurrentpges.pop() >>>>>>>>")
              console.log(page)
              console.log(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<")
              console.log(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<")

              if (page == undefined || page == null) return;
              //page.initData();
              //page.onLoad();
            } */
          })
      },
      complete: function () {
        // complete  
        console.log("pay complete")
      } 
    })
  },

  bindTextAreaBlur: function (e) {
    this.setData({
      buyerMsg: e.detail.value
    })

  },

  showToast(message) {
    App.WxService.showToast({
      title: message,
      icon: 'success',
      duration: 1500,
    })
      .then(() => App.WxService.navigateBack())
  },

/*   selectPayType: function (e) {
    var selectPayId = e.target.dataset.payid;
    console.log("pay>>>>>>>>>>>" + selectPayId);
    //var that = this
    payType = selectPayId;

     for (var i = 0; i < this.data.items.length; i++) {
      if (this.data.items[i].name == selectPayId) {
        this.data.items[i].isSelect = true
      } else {
        this.data.items[i].isSelect = false
      }
    } 


    this.setData({
      items: this.data.items,
    })
  } */
})